<?php

namespace app\yy\admin;

class Thumbnail
{
    public $newFile = '';
    public $err = '';

    public function getSize($image)
    {

        stream_context_set_default( [
            'ssl' => [
                'verify_peer' => false,
                'verify_peer_name' => false,
            ],
        ]);
        $headers = get_headers($image, 1);
        $size = $headers['Content-Length'];
        if($size > 5242880){
            $str = '';
        }elseif($size > 102396){ // 大于 100 kb
            $str = "?x-oss-process=image/resize,w_800,h_800/format,jpg/quality,q_85";
        }else{
            $str = "?x-oss-process=image/resize,w_800,h_800";
        }
        return $str;
    }

    public function get_cache_name($oldfile)
    {
        $file_ext = substr($oldfile, strrpos($oldfile, '.'));
        $md5 = md5($oldfile);
        $file = 'uploads/images/yy/'.$md5 . $file_ext;
        $dir = dirname($file);
        if (!is_dir($dir)) {
            if (!@mkdir($dir, 0777, true)) {
                return false;
            }
        }
        return $file;
    }

    /**
     * 保存远程图片
     * @param $image
     * @return bool
     */
    public function get_file($image)
    {
        if(!$image) return false;
        $this->newFile = $this->get_cache_name($image);
        if (file_exists($this->newFile)) {
            return true;
        }
        if(!($str = $this->getSize($image))){
            $this->err = '图片太大，超过5M';
            return false;
        }
        $image .= $str;
        $option = array('ssl' => array('verify_peer' => false, 'verify_peer_name' => false));
        $content = @file_get_contents($image, false, stream_context_create($option));
        if(!$content){
            $this->err = '图片打开失败，原图片链接有误';
            return false;
        }
        if (file_put_contents($this->newFile, $content)) {
            return true;
        } else {
            $this->err = '图片保存失败';
            return false;
        }
    }

    /**
     * 销毁文件
     * @param $files
     * @return bool
     */
    public function destroyFile($files = []): bool
    {
        if (is_array($files)){
            foreach ($files as $file){
                @unlink($file);
            }
        }else{
            @unlink($this->newFile);
        }
        return true;
    }
}